<template>
    <div>
        <div id="canvasPanel" class="canvas-panel" :style="{ 
            width: activePage.commonStyle.width +'px' ,
            height: activePage.commonStyle.height +'px',
            backgroundColor: activePage.commonStyle.backgroundColor,
            backgroundImage: `url('${activePage.commonStyle.backgroundImage}')`,
            transform: `scale(${scalePercent/100})  translate(0px, 0px)`
        }"  @drop="onDrop($event)" @dragover.prevent="onAllowDrop" @click="onCanvasPanelClick" data-id="canvasPanel">
            <edit-shape
                v-for="item in activePage.elements"
                :key="item.uuid"
                :uuid="item.uuid"
                :defaultStyle="item.commonStyle"
                :style="getCommonStyle({width: item.commonStyle.width, height: item.commonStyle.height, left: item.commonStyle.left,top: item.commonStyle.top,position: item.commonStyle.position})"
                @handleElementClick="handleElementClick(item.uuid)"
                @resize="handleElementResize"
                :active="item.uuid === activeElementUUID"
                @handleKeyup="handleElementCommand">
                <component :style="getCommonStyle({...item.commonStyle, top: 0, left: 0})" :is="item.elName" class="element-on-edit-pane" v-bind="item.propsValue"/>
            </edit-shape>
        </div>
        <!-- 组件菜单功能 -->
        <div class="page-wrapper-menu-operation menu-item-on-edit-panel"
            :style="getMenuOptionsPositionStyle"
            :class="{active: activeElementUUID}">
            <el-tooltip v-for="(item, index) in menuOptions" :key="index" effect="dark" :content="item.title" placement="right">
            <div class="menu-item menu-item-on-edit-panel" @click="handleElementCommand(item.value)">
                <i class="menu-item-on-edit-panel" :class="[item.icon]"></i>
            </div>
            </el-tooltip>
        </div>
    </div>
</template>

<script>
import {mapState, mapGetters} from 'vuex'
// import domtoimage from 'dom-to-image'
import {_qk_register_components_object} from '@src/plugins/index'
// import { createUUID } from '@/common/js/mUtils'
import editShape from '@components/edit-shape'
import editorProjectConfig from '@src/pages/editor/DataModel'
import {camelCase} from 'lodash'
export default {
    data(){
       return {
          getCommonStyle: editorProjectConfig.getCommonStyle,
          menuOptions: [{
					title: '复制',
					icon: 'iconfont iconfuzhi',
					value: 'copy'
				}, {
					title: '删除',
					icon: 'iconfont iconshanchu',
					value: 'delete'
				}, {
					title: '字体放大',
					icon: 'iconfont iconzitifangda',
					value: 'fontA+'
				}, {
					title: '字体缩小',
					icon: 'iconfont iconzitisuoxiao',
					value: 'fontA-'
				}, {
					title: '字体加粗',
					icon: 'iconfont iconzitijiacu',
					value: 'fontB'
				}, {
					title: '图层上移',
					icon: 'iconfont iconziyuan1',
					value: 'layerUp'
				}, {
					title: '图层下移',
					icon: 'iconfont iconxiayiyiceng',
					value: 'layerDown'
				}, {
					title: '图层置顶',
					icon: 'iconfont iconcontrol-top',
					value: 'layerTop'
				}, {
					title: '图层置底',
					icon: 'iconfont iconcontrol-bottom',
					value: 'layerBottom'
		  }],
          editorPaneWidth: 0
       }
    },
    props: {
        // canvas画板缩放
        scale: {
            type: Number,
            default: 1
        }
    },
    mounted(){
        this.$bus.$on('screenCapture', ()=>{
            this.screenCapture()
        })
        console.log(this.activePageUUID)
         console.log(this.projectData)
    },
    watch: {
    },
    methods:{
        /**
         * 元素被点击
         * @param uuid
         */
        handleElementClick(uuid) {
            this.$store.dispatch('setActiveElementUUID', uuid);
            this.$emit('update:activeAttr', '属性')
        },
        /**
         * 移动改变元素大小定位
         * @param pos 当pos有值表示移动中需要实时同步样式变化，pos为undefind时则表示移动结束，记一次历史纪录
         * 鼠标移动完成时才记入历史纪录
         */
        handleElementResize(pos) {
            if (!pos) {
                this.$store.dispatch('addHistoryCache')
                return;
            }
            this.projectData.pages[this.currentPageIndex].elements[this.activeElementIndex].commonStyle.left = pos.left
            // 更新元素commonStyle
            this.projectData.pages[this.currentPageIndex].elements[this.activeElementIndex].commonStyle = {
                ...pos
            }
        },
         getChartX(item){
             return  item.commonStyle.left
         },
         getChartY(item){
             return  item.commonStyle.top
         },
         getWidth(item){
             return  item.commonStyle.width
         },
         getHeight(item){
             return  item.commonStyle.height
         },
        //  getCommonStyle(item){
        //      //读取基本配置
        //      let chartWidth = item.commonStyle.width
        //      let chartHeight = item.commonStyle.height
        //      let chartX = item.commonStyle.left
        //      let chartY = item.commonStyle.top
        //      let zindex = item.commonStyle.zindex || 9
        //      let rotate = item.rotate || 0
        //      return {
        //          'width': chartWidth + 'px',
        //          'height': chartHeight + 'px',
        //          'top':  chartY + 'px',
        //          'left': chartX  + 'px',
        //          'zIndex': zindex,
        //          'transform': `rotate(${rotate}deg)`
        //      }
        //  },
         screenCapture() {
             //截图前把缩放比例设置为100
            //this.$store.dispatch('setScalePercent', 100)
            if(this.scalePercent != 100){
                this.$msgbox({
                    title: '请先将缩放比例调整为100%'
                })
                return
            }
            setTimeout(()=>{
                const node = document.querySelector("#canvasPanel") //this.$refs.canvasPanel
                domtoimage.toPng(node).then( dataUrl => {
                    let params = new FormData()
                    const blob = this.$mUtils.dataURItoBlob(dataUrl)
                    const file = new window.File([blob], +new Date() + '.png', {type: 'image/png'})
                    params.append('file', file);
                    this.$axios.post('/common/uploadFile', params).then(res => {
                        if(res.code === 200){
                            let temp = this.projectData
                            temp.thumbnailImage = res.body
                            this.$store.dispatch('setprojectData', temp)
                        }
                        this.$bus.$emit('doneScreenCapture')
                    }).catch(err => {
                        console.warn(err.message)
                         this.$bus.$emit('doneScreenCapture')
                    })
                })
                .catch(function (error) {
                    console.error('截图出错了!', error);
                    this.$bus.$emit('doneScreenCapture')
                });
            }, 1000)
         },
         async onDrop(e){
             let left = e.offsetX
             let top = e.offsetY
             // let title= e.dataTransfer.getData("title")
             let element = e.dataTransfer.getData('item')? JSON.parse(e.dataTransfer.getData('item')) : {}
            //  this.$axios.post('/componentconfig/detail', {name: title})
            //  .then((res) => {
            //      if(res.code === 200){
            //          let dynamicConfig = res.body
            //          dynamicConfig.uuid = createUUID()
            //          dynamicConfig.props[0].fields[1].value[0].value.value = parseInt(left) 
            //          dynamicConfig.props[0].fields[1].value[1].value.value = parseInt(top)
            //          this.$store.dispatch('addElement', dynamicConfig)
            //      }
            //  })
            //  .catch(e =>{
            //      console.warn(e.message)
            //  })
            let props = this.getComponentProps(element.elName);
            let elInitPosition = {
                top: parseInt(top) || 200,
                left: parseInt(left) || 0
            }
            this.$store.dispatch('addElement', {...element, needProps: props, elInitPosition })
         },
         onAllowDrop(e) {
            // console.log('onAllowDrop', e)
         },
         onComponentActivated(uuid){
             this.$store.dispatch('setActiveElementUUID', uuid);
         },
         onComponentDrag(left, top){
             if(this.activeElementIndex > -1){
                let props = this.projectData.pages[0].elements[this.activeElementIndex].props[0]
                props.fields[1].value[0].value.value = parseInt(left)
                props.fields[1].value[1].value.value = parseInt(top)
                this.$store.dispatch('setprojectData',  this.projectData);
             }
            
         },
         onComponentResize(left, top, width, height){
             if(this.activeElementIndex > -1){
                let props = this.projectData.pages[0].elements[this.activeElementIndex].props[0]
                props.fields[0].value[0].value.value = parseInt(width)
                props.fields[0].value[1].value.value = parseInt(height)
                props.fields[1].value[0].value.value = parseInt(left)
                props.fields[1].value[1].value.value = parseInt(top)
                this.$store.dispatch('setprojectData',  this.projectData);
             }
         },
         onCanvasPanelClick(e){
             if(e.target.dataset.id === "canvasPanel"){
                 this.$store.dispatch('setActiveElementUUID', '');
             }
         },
         onDelete(e){
            let uuid = e.currentTarget.dataset.uuid
            this.$store.dispatch('removeElement', uuid)
         },
         onCopy(){
             if(this.activeElement){
                this.$store.dispatch('addElement', this.activeElement)
             }
         },
         onCopyUUID(e){
            let uuid = e.currentTarget.dataset.uuid
            window.alert(`请复制uuid: ${uuid}`)
         },
        /**
         * 对元素进行操作命令
         */
         handleElementCommand(command) {
             if(!this.activeElement) return
            console.log(command, this.activeElement)
            this.$store.dispatch('elementCommand', command)
         },
        /**
         * 根据elname获取组件默认props数据
         * @param elName
         */
        getComponentProps(elName) {
            let elComponentData
            for (let key in _qk_register_components_object) {
                if (key.toLowerCase() === camelCase(elName).toLowerCase()) {
                    elComponentData = _qk_register_components_object[key];
                    break;
                }
            }
            if (!elComponentData) return {}

            let props = {}
            for (let key in elComponentData.props) {
                props[key] = [Object, Array].includes(elComponentData.props[key].type) ? elComponentData.props[key].default() : elComponentData.props[key].default
            }
            return props;
        },
    },
    computed:{
        ratio(){
            return this.scalePercent / 100
        },
        ...mapState({
            scalePercent: state => state.scale.scalePercent,
            projectData: state => state.editor.projectData,
            activeElementUUID: state => state.editor.activeElementUUID,
            activePageUUID: state => state.editor.activePageUUID,
        }),
        ...mapGetters([
            'currentPageIndex',
            'activeElementIndex',
            'activeElement',
            'activePage'
        ]),
        getMenuOptionsPositionStyle(){
            let both = (this.editorPaneWidth - this.projectData.width * this.ratio) / 2;
            let right = both < 60 ? 400 : both;
            return {
                right: right + 'px'
            }
        }
    },
    components:{
        // 批量注册qk组件
        ..._qk_register_components_object,
        // 画板组件
		[editShape.name]: editShape
    }
}
</script>

<style lang="scss" scoped>
    .canvas-panel{
        position: absolute;
        transform-origin: 0 0;
        top: 60px;
        left: 60px;
        transition: .2s all ease-in-out;
        // background-size: cover,contain;
        // background-position: center,right bottom;
        // background-repeat: no-repeat,no-repeat;
        background: white;
        transform-origin: left top;
        box-shadow: rgba(0,0,0,.5) 0 0 30px 0;
        z-index: 90;
        .draggable.actived{
            border: 2px solid rgb(37,124,245);
            &:hover {
                cursor: pointer;
            }
        }
    }
    .page-wrapper-menu-operation {
        position: fixed;
        right: 0;
        top: 70px;
        width: 0;
        background: white;
        color: #333;
        text-align: center;
        z-index: 1002;
        border-radius: 4px;
        display: none;
        transition: all 0.28s;
        opacity: 0;
        box-shadow: 3px 3px 5px rgb(204, 200, 200);
        .menu-item {
            padding: 10px;
            cursor: pointer;
        &.i {
            font-size: 24px;
            line-height: 30px;
        }
        &:hover {
            background: rgba(37, 165, 137, 0.09);
            color: $primary;
            &.i {
            font-weight: bold;
            font-size: 26px;
            }
        }
        }
        &.active {
            display: block;
            width: 40px;
            opacity: 1;
        }
    }
</style>